# -*- coding: utf-8 -*-
from google.appengine.ext import ndb
from DB.DB_Classes import *
import datetime
import logging


def get_recent_year():
    return "2014"


def create_query_of_get_all_courses_by_sem(currSemester,currUniversity):
    get_year = get_recent_year()
    sem = ndb.Key('n_University', currUniversity,'n_Semester','sem'+get_year+str(currSemester)).get()
    logging.info("read-4-create_query_of_get_all_courses_by_sem")
    return sem.courses_list
    


def create_query_of_faculties(currUniversity,currSemester):
    get_year = get_recent_year()
    faculties = ndb.Key('n_University', currUniversity).get().faculties_and_hugs
    logging.info("read-4-create_query_of_faculties")
    return faculties[get_year+str(currSemester)]


#given currUniversity, currSemester, departNum returns all the courses under that hug 
#ordered by name
def create_query_of_courses_in_hug(currUniversity, currSemester, departNum):
    get_year = get_recent_year()
    hug = ndb.Key('n_University', currUniversity,'n_Hug','hug_'+departNum+'_'+get_year+str(currSemester)).get()
    logging.info("read-10-create_query_of_courses_in_hug")
    return sorted(hug.stats.values(),key=lambda x: x['cName'])

def create_query_of_courses_in_hug_by_day(currUniversity, currSemester, departNum,dayStr):
    get_year = get_recent_year()
    hug = ndb.Key('n_University', currUniversity,'n_Hug','hug_'+departNum+'_'+get_year+str(currSemester)).get()
    logging.info("read-10-create_query_of_courses_in_hug_by_day")
    returnList = []
    for course, st in hug.stats.items():
        for group in st['kvutzaData']:
            if group['days'].__contains__(dayStr) and not returnList.__contains__(st):
                returnList.append(st)
    return sorted(returnList,key=lambda x: x['cName'])

#given currUniversity, currSemester and courseNum returns course information
def create_query_of_course_info(currUniversity, currSemester,departNum, courseNum):
    get_year = get_recent_year()
    hug = ndb.Key('n_University', currUniversity,'n_Hug','hug_'+departNum+'_'+get_year+str(currSemester)).get()
    logging.info("read-10-create_query_of_course_info")
    course = hug.stats.get(courseNum)
    return course

def create_query_of_course_bidding(currUniversity,department,courseNum):
    hug_bid = ndb.Key('n_University', currUniversity,'n_Hug_bid','hugbid_'+department).get()
    logging.info("read-8-create_query_of_course_bidding")
    if hug_bid is None:
        return []
    course_bid = hug_bid.bid.get(courseNum)
    
    if course_bid is None:
        return []
    return course_bid
    

def create_query_of_course_syllabous(currUniversity,courseNum):
    course = ndb.Key('n_University', currUniversity,'n_Course_syllabus','syl_'+ courseNum).get()
    logging.info("read-4-create_query_of_course_syllabous")
    if course is None:
        return ""
    return course.syllabus


def save_data(currUniversity, userid, email, nick,info,sem,courses):
    get_year = get_recent_year()
    user = ndb.Key('n_University', currUniversity,'n_User', userid).get()
    logging.info("read-10-save_data")
    if user is None:
        if sem == 0:
            to_put =   {'displaySettingsArr' : [info['displaySettingsArr'][0],{}], 'coursesInfoArr' : [info['coursesInfoArr'][0],[]]}
        if sem == 1:
            to_put =   {'displaySettingsArr' : [{},info['displaySettingsArr'][1]], 'coursesInfoArr' : [[],info['coursesInfoArr'][1]]}
        if sem == 2:
            to_put =   {'displaySettingsArr' : [info['displaySettingsArr'][0],info['displaySettingsArr'][1]], 'coursesInfoArr' : [info['coursesInfoArr'][0],info['coursesInfoArr'][1]]}
        ancestor_key = ndb.Key('n_University', currUniversity)
        user = n_User(id = userid, userId = userid , userEmail =email,nickName = nick,saved_data = {get_year:to_put},chosenCoursesLists = {"2014":[[],[]]}, parent = ancestor_key)
    else:
        if user.saved_data.get(get_year) is None:
            user.saved_data[get_year] =  {'displaySettingsArr' : [{},{}], 'coursesInfoArr' : [[],[]]}
        if sem == 0:
            user.saved_data[get_year]['displaySettingsArr'][0] = info['displaySettingsArr'][0]
            user.saved_data[get_year]['coursesInfoArr'][0] = info['coursesInfoArr'][0]
        if sem == 1:
            user.saved_data[get_year]['displaySettingsArr'][1] = info['displaySettingsArr'][1]
            user.saved_data[get_year]['coursesInfoArr'][1] = info['coursesInfoArr'][1]
        if sem == 2:
            user.saved_data[get_year]['displaySettingsArr'][0] = info['displaySettingsArr'][0]
            user.saved_data[get_year]['coursesInfoArr'][0] = info['coursesInfoArr'][0]
            user.saved_data[get_year]['displaySettingsArr'][1] = info['displaySettingsArr'][1]
            user.saved_data[get_year]['coursesInfoArr'][1] = info['coursesInfoArr'][1]
    
    #old_courses = user.chosenCoursesLists
    old_courses = user.chosenCoursesLists.get(get_year)
    if old_courses is None:
        to_delete_A = []
        to_delete_B = []
        to_add_A = set(courses[0])
        to_add_B = set(courses[1])
    
    else:
        
        to_delete_A = set(old_courses[0]) - set(courses[0])
        to_delete_B = set(old_courses[1]) - set(courses[1])
        to_add_A = set(courses[0]) - set(old_courses[0])
        to_add_B = set(courses[1]) - set(old_courses[1])
    
    if len(to_delete_A) > 0:
        delete_user_from_course(get_year,"1",userid,to_delete_A,currUniversity)
    if len(to_delete_B) > 0:
        delete_user_from_course(get_year,"2",userid,to_delete_B,currUniversity)
    if len(to_add_A) > 0:
        add_user_to_course(get_year,"1",userid,to_add_A,currUniversity)
    if len(to_add_B) > 0:
        add_user_to_course(get_year,"2",userid,to_add_B,currUniversity)
    
    #user.chosenCoursesLists = courses
    user.chosenCoursesLists[get_year] = courses
    logging.info("write-10-save_data")
    return user.put()

@ndb.transactional
def delete_user_from_course(get_year,currSemester,userid,courses_to_del,currUniversity):
    course_stats = ndb.Key('n_University', currUniversity,'n_Courses_stats','semstats'+get_year + str(currSemester)).get()
    logging.info("read-10-delete_user_from_course")
    if course_stats is None:
        return
    is_changed = False
    for course_to_del in courses_to_del:
        students_list = course_stats.stats.get(course_to_del)
        if students_list is not None and students_list.__contains__(userid):
            students_list.remove(userid)
            is_changed = True
    if is_changed:
        course_stats.put()
        logging.info("write-10-delete_user_from_course")

@ndb.transactional(xg=True)
def add_user_to_course(get_year,currSemester,userid,courses_to_add,currUniversity):
    
    course_stats = ndb.Key('n_University', currUniversity,'n_Courses_stats','semstats'+get_year + str(currSemester)).get()
    logging.info("read-10-add_user_to_course")
    if course_stats is None:
        course_stats = n_Courses_stats(semester = get_year + currSemester)
    is_changed = False
    for course_to_add in courses_to_add:
        students_list = course_stats.stats.get(course_to_add)
        if students_list is None:
            students_list = [userid]
            is_changed = True
        elif not students_list.__contains__(userid):
            students_list.append(userid)
            is_changed = True
        else:
            continue
        course_stats.stats[course_to_add] = students_list
    if is_changed:
        course_stats.put()
        logging.info("write-10-add_user_to_course")


def load_data(currUniversity, userid, email, nick):
    
    get_year = get_recent_year()
    user = ndb.Key('n_University', currUniversity,'n_User', userid).get()
    logging.info("read-10-load_data")
    if user is None:
        ancestor_key = ndb.Key('n_University', currUniversity)
        user = n_User(id= userid,userId = userid , userEmail =email,nickName = nick,saved_data = {get_year:{'displaySettingsArr' : [{},{}], 'coursesInfoArr' : [[],[]]}},parent = ancestor_key)
        logging.info("write-10-load_data")
        user.put()    
    for course in user.saved_data.get(get_year)['coursesInfoArr'][0]:
        curr_course = create_query_of_course_info(currUniversity, "1", course['cNum'][:4], course['cNum'])
        if curr_course is None:
            user.saved_data.get(get_year)['coursesInfoArr'][0].remove(course)
        else:
            course['havurotNum'] = curr_course['havurotNum']
            course['zchutHours'] = curr_course['zchutHours']
            course['kvutzaData'] = curr_course['kvutzaData']
    for course in user.saved_data.get(get_year)['coursesInfoArr'][1]:
        curr_course = create_query_of_course_info(currUniversity, "2", course['cNum'][:4], course['cNum'])
        if curr_course is None:
            user.saved_data.get(get_year)['coursesInfoArr'][1].remove(course)
        else:
            course['havurotNum'] = curr_course['havurotNum']
            course['zchutHours'] = curr_course['zchutHours']
            course['kvutzaData'] = curr_course['kvutzaData']  
    return user.saved_data.get(get_year)

def create_query_of_friend_list_for_course(currUniversity,currSemester,departNum,courseNum,friends):
    get_year = get_recent_year()
    uni = ndb.Key('n_University', currUniversity).get()
    logging.info("read-4-create_query_of_friend_list_for_course")
    course_stats = ndb.Key('n_University', currUniversity,'n_Courses_stats','semstats'+get_year + str(currSemester)).get()
    logging.info("read-4-create_query_of_friend_list_for_course")
    if course_stats is None:
        return [[],0]
    students_list = course_stats.stats.get(courseNum)
    if students_list is None:
        return [[],0]
    friends_in_course = []
    for friend in friends:
        google_id = uni.facebook_to_google_map.get(friend["id"])
        if google_id is None:
            continue
        if students_list.__contains__(google_id):
            friends_in_course.append(friend)
    
    return [friends_in_course,len(students_list)]

@ndb.transactional
def save_fb_and_google_ids(currUniversity,fbID,googleID):
    univ = ndb.Key('n_University', currUniversity).get()
    logging.info("read-4-save_fb_and_google_ids")
    univ.facebook_to_google_map[fbID] = googleID
    logging.info("write-4-save_fb_and_google_ids")
    return univ.put()

def save_events(currUniversity,userid,eventLinkList,email,nick):
    get_year = get_recent_year()
    user = ndb.Key('n_University', currUniversity,'n_User', userid).get()
    logging.info("read-10-save_events")
    if user is None:
        ancestor_key = ndb.Key('n_University', currUniversity)
        user = n_User(id= userid,userId = userid , userEmail =email,nickName = nick,saved_data = {get_year:{'displaySettingsArr' : [{},{}], 'coursesInfoArr' : [[],[]]}},parent = ancestor_key)
    user.events = eventLinkList
    logging.info("write-10-save_events")
    return user.put()

def load_events(currUniversity,userId):
    user = ndb.Key('n_University', currUniversity,'n_User', userId).get()
    if user is None:
        return [[],[],[]]
    logging.info("read-10-load_events")
    return user.events

def getFriendCourses(currUniversity,userFacebookId):
    get_year = get_recent_year()
    univ = n_University.get_by_id(currUniversity)
    logging.info("read-4-getFriendCourses")
    gID = univ.facebook_to_google_map.get(userFacebookId)
    user = ndb.Key('n_University', currUniversity,'n_User', gID).get()
    logging.info("read-8-getFriendCourses")
    return user.saved_data[get_year]['displaySettingsArr']
